import app from '@/app'
import { user, update, logout, login } from '@/api/manage/user'

import base from '@/app/model'

// 继承总模型
const model = new base;

model.get = () => {
  return new Promise((resolve, jeject) => {
    app.ui.loading()
    user().then(res => {
      model.setData(res)
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

model.update = (...arge) => {
  return new Promise((resolve, jeject) => {
    update(...arge).then(res => {
      model.get()
      app.ui.message('success', res.message)
      resolve(res)
    }).catch(res => {
      app.ui.message('error', 'error.' + res.message)
      jeject(res)
    })
  })
}

model.login = (...arge) => {
  return new Promise((resolve, jeject) => {
    app.ui.loading()
    login(...arge).then(res => {
      // 存储Token
      app.token(res.token)
      // 进入 User 客户端
      app.route.to('/user')
      resolve(res)
    }).catch(res => {
      app.ui.message('error', res.message)
      jeject(res)
    }).finally(() => {
      app.ui.loadingClose()
    })
  })
}

model.logout = () => {
  return new Promise((resolve, jeject) => {
    logout().then(res => {
      model.setData({})
      // 清除token
      app.logout()
      resolve(res)
    }).catch(res => {
      jeject(res)
    })
  })
}

export default model